package com.yf1706.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yf1706.bean.BaseSalary;
import com.yf1706.bean.Emp;
import com.yf1706.bean.EmpAttachment;
import com.yf1706.bean.EmpCommunicationInfo;
import com.yf1706.bean.EmpDetailInfo;
import com.yf1706.bean.EmpEducationHistory;
import com.yf1706.bean.EmpFamilyInfo;
import com.yf1706.bean.EmpSkillCertificate;
import com.yf1706.bean.EmpWorkHistory;
import com.yf1706.bean.RelationshipSetting;
import com.yf1706.bean.SexSetting;
import com.yf1706.bean.User;
import com.yf1706.service.BaseSalaryService;
import com.yf1706.service.DepService;
import com.yf1706.service.EmpService;
import com.yf1706.service.SettingService;
import com.yf1706.tools.ListTools;
import com.yf1706.tools.UploadDownloadTool;
import com.yf1706.tools.UserTools;
import com.yf1706.vo.EmpBasicVO;
import com.yf1706.vo.Information;

@Controller
@RequestMapping("emp")
public class EmpController {
	@Autowired
	private EmpService es;
	@Autowired
	private SettingService ss;
	@Autowired
	private DepService ds;
	@Autowired
	private UserTools ut;
	@Autowired
	private ListTools lt;
	@Autowired
	private UploadDownloadTool udt;
	@Autowired
	private BaseSalaryService bService;

	@RequestMapping("empInfo")
	public ModelAndView empInfo(String empId) {
		System.out.println("进入empInfo...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_info");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empBasic")
	public ModelAndView empBasic(String empId) {
		System.out.println("进入empBasic...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_basic");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empBasicEdit")
	public ModelAndView empBasicEdit(String empId) {
		System.out.println("进入empBasicEdit");
		ModelAndView mv = new ModelAndView("zxy/emp_basic_edit");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empDetail")
	public ModelAndView empDetail(String empId) {
		System.out.println("进入empDetail...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_detail");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empDetailEdit")
	public ModelAndView empDetailEdit(String empId) {
		System.out.println("进入empDetail...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_detail_edit");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empCommunication")
	public ModelAndView empCommunication(String empId) {
		System.out.println("进入empBasic...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_communication");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empCommunicationEdit")
	public ModelAndView empCommunicationEdit(String empId) {
		System.out.println("进入empCommunicationEdit...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_communication_edit");
		mv.addObject("empId", empId);
		mv.addObject("emp", this.findEmpById(empId));
		return mv;
	}

	@RequestMapping("empFamilyInfo")
	public ModelAndView empFamilyInfo(String empId) {
		System.out.println("进入empFamilyInfo...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_family_info");
		mv.addObject("empId", empId);
		List<EmpFamilyInfo> list = es.findEmpFamilyInfoByEmpId(Integer.valueOf(empId));
		Object empFamilyInfos = JSON.toJSON(list);
		mv.addObject("empFamilyInfos", empFamilyInfos);
		return mv;
	}

	@RequestMapping("empWorkHistory")
	public ModelAndView empWorkHistory(String empId) {
		System.out.println("进入empWorkHistory...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_work_history");
		mv.addObject("empId", empId);
		List<EmpWorkHistory> list = es.findEmpWorkHistoryByEmpId(Integer.valueOf(empId));
		Object empWorkHistories = JSON.toJSON(list);
		mv.addObject("empWorkHistories", empWorkHistories);
		return mv;
	}

	@RequestMapping("empEducationHistory")
	public ModelAndView empEducationHistory(String empId) {
		System.out.println("进入empBasic...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_education_history");
		mv.addObject("empId", empId);
		List<EmpEducationHistory> list = es.findEmpEducationHistoryByEmpId(Integer.valueOf(empId));
		Object empEducationHistories = JSON.toJSON(list);
		mv.addObject("empEducationHistories", empEducationHistories);
		return mv;
	}

	@RequestMapping("empSkillCertificate")
	public ModelAndView empSkillCertificate(String empId) {
		System.out.println("进入empBasic...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_skill_certificate");
		mv.addObject("empId", empId);
		List<EmpSkillCertificate> list = es.findEmpSkillCertificateByEmpId(Integer.valueOf(empId));
		Object empSkillCertificates = JSON.toJSON(list);
		mv.addObject("empSkillCertificates", empSkillCertificates);
		return mv;
	}

	@RequestMapping("empAttachment")
	public ModelAndView empAttachment(String empId) {
		System.out.println("进入empBasic...empId=" + empId);
		ModelAndView mv = new ModelAndView("zxy/emp_attachment");
		mv.addObject("empId", empId);
		List<EmpAttachment> list = es.findEmpAttachmentByEmpId(Integer.valueOf(empId));
		Object empAttachments = JSON.toJSON(list);
		mv.addObject("empAttachments", empAttachments);
		return mv;
	}
	//选择员工页面
	@RequestMapping("selectEmp")
	public ModelAndView selectEmp() {
		ModelAndView mv=new ModelAndView("zxy/emp_select");
		return mv;
	}
	// 以上为跳转页面方法

	// 新增员工
	@RequestMapping("addEmpInfo")
	@ResponseBody
	public Information addEmpInfo(EmpBasicVO ebvo,HttpServletRequest request) {
		System.out.println("进入addEmpInfo...");
		System.out.println(ebvo);
		Emp emp=new Emp();
		emp.setEmpName(ebvo.getEmpName());
		emp.setDep(ds.findByDepId(ebvo.getDepId()));
		emp.setPostSetting(ss.findPostSettingByPostId(ebvo.getPostId()));
		emp.setRankSetting(ss.findRanktSettingByRankId(ebvo.getRankId()));
		emp.setWorkStatusId((byte)ebvo.getWorkStatus());
		emp.setPassword(ebvo.getPassword());
		es.saveEmpAllById(emp);
		
		EmpDetailInfo edi=new EmpDetailInfo();
		edi.setEmp(emp);
		es.saveEmpDetailInfo(edi);
		
		EmpCommunicationInfo eci=new EmpCommunicationInfo();
		eci.setTel1(ebvo.getTel());
		eci.setEmp(emp);
		es.saveEmpCommunicationInfo(eci);
		
		int empId=emp.getEmpId();
		BaseSalary bSalary = new BaseSalary();
		bSalary.setBaseSalarySob(bService.findSobByID(ebvo.getBaseSalarySobId()));
		bSalary.setEmp(bService.findEmpByID(empId));
		bSalary.setBaseSalaryValue(ebvo.getBaseSalary());
		try {
			bSalary.setSalaryBeginDate(new SimpleDateFormat("yyyy-MM-dd").parse(ebvo.getSalaryBeginDate()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		User user=ut.getUser(request);
		bSalary.setMender(es.queryBasicById(user.getUserId()).getEmpName());
		bSalary.setMendDate(new Date());
		bService.saveBS(bSalary);
		return Information.SUCCESS;
	}
	
	// 根据员工编号返回所有员工信息的对象
	@RequestMapping("findEmpById")
	@ResponseBody
	public Emp findEmpById(String empId) {
		System.out.println("进入findEmpById...empId=" + empId);
		// System.out.println(es.findEmpById(Integer.valueOf(empId)));
		return es.findEmpById(Integer.valueOf(empId));
	}

	// 根据员工编号修改对应员工的姓名信息
	@RequestMapping("updateEmp")
	public void updateEmp(HttpServletRequest request, HttpServletResponse response) {
		try {
			PrintWriter out = response.getWriter();
			User user=(User) request.getSession().getAttribute("user");

			System.out.println("进入updateEmp");
			System.out.println(request.getParameter("empName"));
			System.out.println(request.getParameter("englishName"));
			System.out.println("depId:" + request.getParameter("depId"));
			System.out.println("postId:" + request.getParameter("postId"));
			System.out.println("rankId:" + request.getParameter("rankId"));
			int empId = Integer.valueOf(request.getParameter("empId"));
			String empName = request.getParameter("empName");
			String englishName = request.getParameter("englishName");
			Emp emp = es.findEmpById(empId);
			emp.setEmpName(empName);
			emp.setEnglishName(englishName);
			Date updateTime = new Date(new java.util.Date().getTime());
			emp.setUpdateEmp(es.queryById(user.getEmp().getEmpId()).getEmpName());
			emp.setUpdateTime(updateTime);

			es.saveEmpAllById(emp);

			out.print("1");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 根据员工编号修改员工的详细信息
	@RequestMapping("updateEmpDetailInfo")
	public void updateEmpDetailInfo(HttpServletRequest request, HttpServletResponse response) {
		try {
			PrintWriter out = response.getWriter();


			System.out.println("进入updateEmpDetailInfo");
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			// 获取员工详细信息参数
			int empDetailInfoId = Integer.valueOf(request.getParameter("empDetailInfoId"));
			int empId = Integer.valueOf(request.getParameter("empId"));
			byte sexId = Byte.valueOf(request.getParameter("empSexId"));
			String idCard = request.getParameter("idCard");
			System.out.println("idCard" + idCard);
			byte educationId = Byte.valueOf(request.getParameter("educationId"));
			String hireDateStr = request.getParameter("hireDate");
			String correctedDateStr = request.getParameter("correctedDate");
			String resignDateStr = request.getParameter("resignDate");
			String birthdayStr = request.getParameter("birthday");

			// 获取日期
			Date birthday;
			Date hireDate;
			Date correctedDate;
			Date resignDate;
			if (!birthdayStr.equals("")) {
				birthday = simpleDateFormat.parse(request.getParameter("birthday"));
			} else {
				birthday = null;
			}
			if (!hireDateStr.equals("")) {
				hireDate = simpleDateFormat.parse(request.getParameter("hireDate"));
			} else {
				hireDate = null;
			}
			if (!correctedDateStr.equals("")) {
				correctedDate = simpleDateFormat.parse(request.getParameter("correctedDate"));
			} else {
				correctedDate = null;
			}
			if (!resignDateStr.equals("")) {
				resignDate = simpleDateFormat.parse(request.getParameter("resignDate"));
			} else {
				resignDate = null;
			}
			System.out.println(hireDate + "---" + correctedDate + "---" + resignDate);
			byte politicalId = Byte.valueOf(request.getParameter("politicalId"));
			byte healthId = Byte.valueOf(request.getParameter("healthId"));
			String nationality = request.getParameter("nationality");
			byte nationId = Byte.valueOf(request.getParameter("nationId"));
			String maritalStatus = request.getParameter("maritalStatus");

			EmpDetailInfo empDetailInfo = es.findEmpDetailInfoById(empDetailInfoId);
			empDetailInfo.setSexSetting(ss.findSexBySexId(sexId));
			empDetailInfo.setIdCard(idCard);
			empDetailInfo.setBirthday(birthday);
			empDetailInfo.setEducationSetting(ss.findEducationByEducationId(educationId));
			empDetailInfo.setHireDate(hireDate);
			empDetailInfo.setCorrectedDate(correctedDate);
			empDetailInfo.setResignDate(resignDate);
			empDetailInfo.setPoliticalSetting(ss.findPoliticalByPoliticalId(politicalId));
			empDetailInfo.setHealthSetting(ss.findHealthByHealthId(healthId));
			empDetailInfo.setNationSetting(ss.findNationByNationId(nationId));
			empDetailInfo.setNationality(nationality);
			empDetailInfo.setMaritalStatus(maritalStatus);

			System.out.println(empDetailInfo);
			es.saveEmpDetailInfo(empDetailInfo);

			out.print("1");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				response.getWriter().print("3");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 根据员工编号更新照片地址
	@RequestMapping("updateEmpPhotoByEmpId")
	public void updateEmpPhotoByEmpId(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println("进入updateEmpPhotoByEmpId");
		response.setCharacterEncoding("utf-8");
		PrintWriter out;
		Map map = new HashMap<>();
		try {
			out = response.getWriter();
			// 将文件上传，并返回文件路径
			String photo = udt.fileUpload(file, request);
			int empId = Integer.parseInt(request.getParameter("empId"));
			es.updateEmpPhotoByEmpId(empId, udt.PATH + "/" + photo);
			System.out.println(empId + ":" + photo);
			map.put("success", true);
			map.put("msg", "编辑成功");
			map.put("src", udt.PATH + "/" + photo);
			String msg = JSON.toJSONString(map);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "编辑失败");
			String msg = JSON.toJSONString(map);
			try {
				response.getWriter().print(msg);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	// 根据员工编号修改员工的通讯信息
	@RequestMapping("updateEmpCommunicationInfo")
	public void updateEmpCommunicationInfo(HttpServletRequest request, HttpServletResponse response) {
		try {
			PrintWriter out = response.getWriter();

			System.out.println("进入updateEmpCommunicationInfo");
			// 获取员工通讯信息参数
			String address = request.getParameter("address");
			String city = request.getParameter("city");
			String contactPerson = request.getParameter("contactPerson");
			String contactTel = request.getParameter("contactTel");
			String country = request.getParameter("country");
			String currentAddress = request.getParameter("currentAddress");
			String district = request.getParameter("district");
			String email = request.getParameter("email");
			String fax = request.getParameter("fax");
			int communicationId = Integer.parseInt(request.getParameter("communicationId"));
			String postalCode = request.getParameter("postalCode");
			String province = request.getParameter("province");
			String street = request.getParameter("street");
			String tel1 = request.getParameter("tel1");
			String tel2 = request.getParameter("tel2");

			EmpCommunicationInfo eci = es.findEmpCommunicationById(communicationId);
			eci.setAddress(address);
			eci.setCity(city);
			eci.setContactPerson(contactPerson);
			eci.setContactTel(contactTel);
			eci.setCountry(country);
			eci.setCurrentAddress(currentAddress);
			eci.setDistrict(district);
			eci.setEmail(email);
			eci.setFax(fax);
			eci.setPostalCode(postalCode);
			eci.setProvince(province);
			eci.setStreet(street);
			eci.setTel1(tel1);
			eci.setTel2(tel2);
			System.out.println(eci);
			es.saveEmpCommunicationInfo(eci);

			out.print("1");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 添加对应员工编号的家庭信息记录
	@RequestMapping("addEmpFamilyInfo")
	public void addEmpFamilyInfo(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out;
		try {
			out = response.getWriter();
			System.out.println("进入addEmpFamilyInfo");
			System.out.println("empId" + request.getParameter("empId"));
			int empId = Integer.valueOf(request.getParameter("empId"));
			String name = request.getParameter("name");
			byte relationshipId = Byte.valueOf(request.getParameter("relationship"));
			String tel = request.getParameter("tel");
			String fax = request.getParameter("fax");
			String email = request.getParameter("email");
			String address = request.getParameter("address");
			String remark = request.getParameter("remark");
			System.out.println(empId + "--" + relationshipId + "--" + tel + "--" + fax + "--" + email + "--" + address
					+ "--" + remark);
			RelationshipSetting rss = ss.findRelationshipSettingById(relationshipId);
			EmpFamilyInfo efi = new EmpFamilyInfo(address, email, fax, name, rss, remark, tel);
			es.addEmpFamilyInfoByEmpId(empId, efi);
			Map map = new HashMap<>();
			map.put("success", true);
			map.put("msg", "添加成功");
			String msg = JSON.toJSONString(map);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 删除对应编号的家庭信息记录
	@RequestMapping("deleteEmpFamilyInfoById")
	public void deleteEmpFamilyInfoById(HttpServletRequest request, HttpServletResponse response) {
		Map map = new HashMap<>();
		PrintWriter out;
		try {
			out = response.getWriter();
			System.out.println("进入deleteEmpFamilyInfoById");
			System.out.println("id_arr" + request.getParameter("id_arr"));
			JSONArray arr = JSONArray.parseArray(request.getParameter("id_arr"));
			for (Object obj : arr) {
				int id = (int) obj;
				es.deleteEmpFamilyInfoByEmpId(id);
			}
			map.put("success", true);
			map.put("msg", "删除成功");
			String msg = JSON.toJSONString(map);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 修改对应编号的家庭信息记录
	@RequestMapping("updateEmpFamilyInfoById")
	public void updateEmpFamilyInfoById(HttpServletRequest request, HttpServletResponse response) {
		Map map = new HashMap<>();
		PrintWriter out;
		try {
			out = response.getWriter();

			System.out.println("进入updateEmpFamilyInfoById");

			int empId = Integer.valueOf(request.getParameter("empId"));
			int id = Integer.valueOf(request.getParameter("id"));
			String name = request.getParameter("name");
			byte relationshipId = Byte.valueOf(request.getParameter("relationship"));
			String tel = request.getParameter("tel");
			String fax = request.getParameter("fax");
			String email = request.getParameter("email");
			String address = request.getParameter("address");
			String remark = request.getParameter("remark");
			System.out.println(id + "--" + relationshipId + "--" + tel + "--" + fax + "--" + email + "--" + address
					+ "--" + remark);
			RelationshipSetting rss = ss.findRelationshipSettingById(relationshipId);
			EmpFamilyInfo efi = new EmpFamilyInfo(address, email, fax, name, rss, remark, tel);
			efi.setId(id);
			es.updateEmpFamilyInfoById(empId, efi);

			map.put("success", true);
			map.put("msg", "编辑成功");
			String msg = JSON.toJSONString(map);
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// mybatis查询所有员工
	@RequestMapping("queryAllEmp")
	@ResponseBody
	public Map<String, Object> queryAllEmp(int page, int rows) {
		Page<Emp> pages = PageHelper.startPage(page, rows);
		List<Emp> list = es.queryAllEmp();
		/* UserTools.listEmpIdFormat(list); */
		for (Iterator<Emp> it = list.iterator(); it.hasNext();) {
			Emp emp = it.next();
			System.out.println(emp);
		}
		long total = pages.getTotal();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", total);
		map.put("rows", list);
		return map;
	}

	// 根据搜索词返回对应的员工集合
	@RequestMapping("queryBySearch")
	@ResponseBody
	public Map<String, Object> queryBySearch(int page, int rows,HttpServletRequest request) {
		System.out.println("进入queryBySearch...page:" + page + ",rows:" + rows);
		boolean showResign = Boolean.parseBoolean(request.getParameter("showResign"));
		String beginDateStr = request.getParameter("beginDate");
		String endDateStr = request.getParameter("endDate");
		String searchValue = request.getParameter("searchValue");
		System.out.println(showResign + "-" + beginDateStr + "-" + endDateStr + "-" + searchValue);
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
		Date beginDate=null;
		Date endDate=null;
		try {
			if (!beginDateStr.equals("") && beginDateStr != null) {
				beginDate = sdf.parse(beginDateStr);
			}
			if (!endDateStr.equals("") && endDateStr != null) {
				endDate = sdf.parse(endDateStr);
				System.out.println(endDate.toLocaleString());
			}

			Page<Emp> pages = PageHelper.startPage(page, rows);
			List<Emp> list = es.queryBySearch(searchValue, beginDate, endDate, showResign);
			UserTools.listEmpIdFormat(list);
			for (Iterator<Emp> it = list.iterator(); it.hasNext();) {
				Emp emp = it.next();
				System.out.println(emp);
			}
			long total = pages.getTotal();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);
			System.out.println(Arrays.toString(map.entrySet().toArray()));
			return map;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
